package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.enums.ReconciliationStatusEnums;
import com.ytjj.qmyx.supplychain.common.enums.ReturnGoodsStatusEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.dto.ReconciliationDTO;
import com.ytjj.qmyx.supplychain.common.model.request.ReconciliationOtherMoneyRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReconciliationRequest;
import com.ytjj.qmyx.supplychain.common.model.response.OtherMoneyResponse;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.sound.sampled.Line;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReconciliationService {

    @Resource
    private ReconciliationMapper reconciliationMapper;
    @Resource
    private ReconciliationOrdersMapper reconciliationOrdersMapper;
    @Resource
    private ReconciliationReturnMapper reconciliationReturnMapper;
    @Resource
    private ReconciliationOtherMoneyMapper reconciliationOtherMoneyMapper;

    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private BankerInfoMapper bankerInfoMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;

    /**
     * 根据条件获取账单
     *
     * @param request
     * @return
     */
    public CommonResult getReconciliationList(ReconciliationRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<YxReconciliation> list = reconciliationMapper.getReconciliationList(request);
        CommonPage<YxReconciliation> yxReconciliationCommonPage = CommonPage.restPage(list);
        List<YxReconciliation> collect = list.stream().map(item -> {
            item.setSettlementAmount(item.getSettlementAmount().add(item.getOtherAmount()));
            return item;
        }).collect(Collectors.toList());
        yxReconciliationCommonPage.setList(collect);
        return CommonResult.success(yxReconciliationCommonPage);
    }

    public CommonResult getReconciliationOrders(Integer reconciliationId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(YxReconciliationOrders.class);
        example.createCriteria().andEqualTo("reconciliationId", reconciliationId);
        example.setOrderByClause("order_date desc");
        List<YxReconciliationOrders> list = reconciliationOrdersMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(CommonPage.restPage(new ArrayList<>()));
        }
        List<Integer> bankerIds = list.stream().map(YxReconciliationOrders::getBankerId).collect(Collectors.toList());
        Example bankerExample = new Example(YxBanker.class);
        bankerExample.createCriteria().andIn("id", bankerIds);
        bankerExample.selectProperties("id", "name");
        List<YxBanker> yxBankers = bankerMapper.selectByExample(bankerExample);
        list.stream().forEach(item -> {
            List<YxBanker> collect = yxBankers.stream().filter(yxBanker -> item.getBankerId().equals(yxBanker.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                item.setBankerName(collect.get(0).getName());
            }
        });
        return CommonResult.success(CommonPage.restPage(list));
    }

    public CommonResult getReconciliationReturn(Integer reconciliationId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(YxReconciliationReturn.class);
        example.createCriteria().andEqualTo("reconciliationId", reconciliationId);
        example.setOrderByClause("return_date desc");
        List<YxReconciliationReturn> list = reconciliationReturnMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(CommonPage.restPage(new ArrayList<>()));
        }
        List<Integer> bankerIds = list.stream().map(YxReconciliationReturn::getBankerId).collect(Collectors.toList());
        Example bankerExample = new Example(YxBanker.class);
        bankerExample.createCriteria().andIn("id", bankerIds);
        bankerExample.selectProperties("id", "name");
        List<YxBanker> yxBankers = bankerMapper.selectByExample(bankerExample);
        list.stream().forEach(item -> {
            List<YxBanker> collect = yxBankers.stream().filter(yxBanker -> item.getBankerId().equals(yxBanker.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                item.setBankerName(collect.get(0).getName());
            }
        });
        return CommonResult.success(CommonPage.restPage(list));
    }

    /**
     * 日结 每天晚上0:00:00 运行一次 (前一天的 0:00:00 - 23:59:59)
     */
    public void verifyReconciliationByDay(String dateStr) {
        //日结的供应商
        List<YxBanker> yxBankers = getBankersByRepayType(1);
        if (CollectionUtils.isEmpty(yxBankers)) {
            return;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //设置时间格式
        //供应商详情
        List<Integer> bankerIds = yxBankers.stream().map(YxBanker::getId).collect(Collectors.toList());
        List<YxBankerInfo> yxBankerInfos = getBankerInfoByBankerIds(bankerIds);
        //获取账单时间
        Date dNow = null;
        if (StringUtils.isNotBlank(dateStr)){
            try {
                dNow = sdf1.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            dNow = new Date();
        }
        Date dBefore;
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
        dBefore = calendar.getTime(); //得到前一天的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        String startTime1 = sdf.format(dBefore); //格式化前一天
        String startTimeStr = startTime1 + " 00:00:00";
        String endTimeStr = startTime1 + " 23:59:59";
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf1.parse(startTimeStr);
            endTime = sdf1.parse(endTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //获取时间内的订单
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectRecinciliationByTime(bankerIds, startTime, endTime);
        //获取时间内的售后完成单
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectRecinciliationByTime(bankerIds, startTime, endTime, ReturnGoodsStatusEnums.REFUND.getStatus());
        //售后完成单的订单发货状态
        List<YxBankerOrder> yxBankerOrders = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationReturnList)) {
            List<String> childOrderNoList = reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList());
            yxBankerOrders = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
        }
        Date finalStartTime = startTime;
        Date finalEndTime = endTime;
        List<YxBankerOrder> finalYxBankerOrders = yxBankerOrders;
        yxBankers.stream().forEach(banker -> {
            List<YxBankerInfo> collectBankerInfo = yxBankerInfos.stream().filter(yxBankerInfo -> banker.getId().equals(yxBankerInfo.getBankerId())).collect(Collectors.toList());
            YxBankerInfo yxBankerInfo = null;
            if (!CollectionUtils.isEmpty(collectBankerInfo)) {
                yxBankerInfo = collectBankerInfo.get(0);
            }
            List<YxReconciliationOrders> collectOrder = reconciliationOrdersList.stream().filter(orders -> banker.getId().equals(orders.getBankerId())).collect(Collectors.toList());
            Integer orderSize = 0;
            BigDecimal ordersMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collectOrder)) {
                orderSize = collectOrder.size();
                ordersMoney = collectOrder.stream()
                        .filter(order -> order.getTotalMoney() != null)
                        .map(YxReconciliationOrders::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            List<YxReconciliationReturn> returnOrders = reconciliationReturnList.stream().filter(YxReconciliationReturn -> banker.getId().equals(YxReconciliationReturn.getBankerId())).collect(Collectors.toList());
            Integer returnSize = 0;
            BigDecimal returnMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(returnOrders)) {
                returnSize = returnOrders.size();
                returnMoney = returnOrders.stream()
                        .filter(returnGoods -> returnGoods.getTotalMoney() != null)
                        .map(YxReconciliationReturn::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            Integer orderSum = orderSize + returnSize;
            if (0 == orderSum) {
                return;
            }
            //账单
            YxReconciliation yxReconciliation = YxReconciliation.builder()
                    .bankerId(banker.getId())
                    .status(ReconciliationStatusEnums.WAIT.getStatus())
                    .reconciliationStartDate(finalStartTime)
                    .reconciliationEndDate(finalEndTime)
                    .orderSum(orderSum)
                    .settlementAmount(ordersMoney.subtract(returnMoney))
                    .creditCardNumbers(null != yxBankerInfo ? yxBankerInfo.getCreditCardNumbers() : "")
                    .bankHouse(null != yxBankerInfo ? yxBankerInfo.getBankHouse() : "")
                    .failRemark(null)
                    .createTime(new Date())
                    .ordersAmount(ordersMoney)
                    .returnGoodsAmount(returnMoney)
                    .otherAmount(BigDecimal.ZERO)
                    .build();
            Integer count = reconciliationMapper.insertSelective(yxReconciliation);
            if (count < 1) {
                log.error("==========插入账单异常==========yxReconciliation::{}", JSONObject.toJSONString(yxReconciliation));
                return;
            }
            //插入账单的订单信息
            collectOrder.stream().forEach(order -> {
                order.setBankerId(banker.getId());
                order.setReconciliationId(yxReconciliation.getId());
                reconciliationOrdersMapper.insertSelective(order);
            });
            //插入账单的售后完成信息
            returnOrders.stream().forEach(returnOrder -> {
                List<YxBankerOrder> collect = finalYxBankerOrders.stream().filter(item -> returnOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    returnOrder.setDeliverStatus(Integer.valueOf(collect.get(0).getOrderStatus()));
                }
                returnOrder.setBankerId(banker.getId());
                returnOrder.setReconciliationId(yxReconciliation.getId());
                reconciliationReturnMapper.insertSelective(returnOrder);
            });
        });
    }

    /**
     * 周结 周一晚上00:00:00 运行一次 (上周星期一的 0:00:00 - 上周星期天23:59:59)
     */
    public void verifyReconciliationByWeek() {
        //供应商
        List<YxBanker> yxBankers = getBankersByRepayType(2);
        if (CollectionUtils.isEmpty(yxBankers)) {
            return;
        }
        //供应商详情
        List<Integer> bankerIds = yxBankers.stream().map(YxBanker::getId).collect(Collectors.toList());
        List<YxBankerInfo> yxBankerInfos = getBankerInfoByBankerIds(bankerIds);
        //获取账单时间
        Date startTime = null;
        Date endTime = null;
        Map<String, Object> upWeekMap = upWeek();
        Timestamp weekStart = (Timestamp) upWeekMap.get("weekStart");
        Timestamp weekEnd = (Timestamp) upWeekMap.get("weekEnd");
        startTime = new Date(weekStart.getTime());
        endTime = new Date(weekEnd.getTime());
        //获取时间内的订单
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectRecinciliationByTime(bankerIds, startTime, endTime);
        //获取时间内的售后完成单
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectRecinciliationByTime(bankerIds, startTime, endTime, ReturnGoodsStatusEnums.REFUND.getStatus());
        //售后完成单的订单发货状态
        List<YxBankerOrder> yxBankerOrders = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationReturnList)) {
            List<String> childOrderNoList = reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList());
            yxBankerOrders = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
        }
        Date finalStartTime = startTime;
        Date finalEndTime = endTime;
        List<YxBankerOrder> finalYxBankerOrders = yxBankerOrders;
        yxBankers.stream().forEach(banker -> {
            List<YxBankerInfo> collectBankerInfo = yxBankerInfos.stream().filter(yxBankerInfo -> banker.getId().equals(yxBankerInfo.getBankerId())).collect(Collectors.toList());
            YxBankerInfo yxBankerInfo = null;
            if (!CollectionUtils.isEmpty(collectBankerInfo)) {
                yxBankerInfo = collectBankerInfo.get(0);
            }
            List<YxReconciliationOrders> collectOrder = reconciliationOrdersList.stream().filter(orders -> banker.getId().equals(orders.getBankerId())).collect(Collectors.toList());
            Integer orderSize = 0;
            BigDecimal ordersMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collectOrder)) {
                orderSize = collectOrder.size();
                ordersMoney = collectOrder.stream()
                        .filter(order -> order.getTotalMoney() != null)
                        .map(YxReconciliationOrders::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            List<YxReconciliationReturn> returnOrders = reconciliationReturnList.stream().filter(YxReconciliationReturn -> banker.getId().equals(YxReconciliationReturn.getBankerId())).collect(Collectors.toList());
            Integer returnSize = 0;
            BigDecimal returnMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(returnOrders)) {
                returnSize = returnOrders.size();
                returnMoney = returnOrders.stream()
                        .filter(returnGoods -> returnGoods.getTotalMoney() != null)
                        .map(YxReconciliationReturn::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            Integer orderSum = orderSize + returnSize;
            if (0 == orderSum) {
                return;
            }
            //账单
            YxReconciliation yxReconciliation = YxReconciliation.builder()
                    .bankerId(banker.getId())
                    .status(ReconciliationStatusEnums.WAIT.getStatus())
                    .reconciliationStartDate(finalStartTime)
                    .reconciliationEndDate(finalEndTime)
                    .orderSum(orderSum)
                    .settlementAmount(ordersMoney.subtract(returnMoney))
                    .creditCardNumbers(null != yxBankerInfo ? yxBankerInfo.getCreditCardNumbers() : "")
                    .bankHouse(null != yxBankerInfo ? yxBankerInfo.getBankHouse() : "")
                    .failRemark(null)
                    .createTime(new Date())
                    .ordersAmount(ordersMoney)
                    .returnGoodsAmount(returnMoney)
                    .otherAmount(BigDecimal.ZERO)
                    .build();
            Integer count = reconciliationMapper.insertSelective(yxReconciliation);
            if (count < 1) {
                log.error("==========插入账单异常==========yxReconciliation::{}", JSONObject.toJSONString(yxReconciliation));
                return;
            }
            //插入账单的订单信息
            collectOrder.stream().forEach(order -> {
                order.setBankerId(banker.getId());
                order.setReconciliationId(yxReconciliation.getId());
                reconciliationOrdersMapper.insertSelective(order);
            });
            //插入账单的售后完成信息
            returnOrders.stream().forEach(returnOrder -> {
                List<YxBankerOrder> collect = finalYxBankerOrders.stream().filter(item -> returnOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    returnOrder.setDeliverStatus(Integer.valueOf(collect.get(0).getOrderStatus()));
                }
                returnOrder.setBankerId(banker.getId());
                returnOrder.setReconciliationId(yxReconciliation.getId());
                reconciliationReturnMapper.insertSelective(returnOrder);
            });
        });
    }

    /**
     * 月结 1号晚上00:00:00 运行一次 (上个月的1号00:00:00 - 上个月的最后一天的23:59:59)
     */
    public void verifyReconciliationByMonth() {
        //供应商
        List<YxBanker> yxBankers = getBankersByRepayType(4);
        if (CollectionUtils.isEmpty(yxBankers)) {
            return;
        }
        //供应商详情
        List<Integer> bankerIds = yxBankers.stream().map(YxBanker::getId).collect(Collectors.toList());
        List<YxBankerInfo> yxBankerInfos = getBankerInfoByBankerIds(bankerIds);
        //获取账单时间
        Date startTime = null;
        Date endTime = null;
        Map<String, Object> upMonth = null;
        try {
            upMonth = getLastMonthTime(1);
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdfs.parse(upMonth.get("startDate").toString());
            endTime = sdfs.parse(upMonth.get("endDate").toString());
        } catch (Exception e) {
            log.error("===={}", e);
        }
        //获取时间内的订单
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectRecinciliationByTime(bankerIds, startTime, endTime);
        //获取时间内的售后完成单
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectRecinciliationByTime(bankerIds, startTime, endTime, ReturnGoodsStatusEnums.REFUND.getStatus());
        //售后完成单的订单发货状态
        List<YxBankerOrder> yxBankerOrders = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationReturnList)) {
            List<String> childOrderNoList = reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList());
            yxBankerOrders = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
        }
        Date finalStartTime = startTime;
        Date finalEndTime = endTime;
        List<YxBankerOrder> finalYxBankerOrders = yxBankerOrders;
        yxBankers.stream().forEach(banker -> {
            List<YxBankerInfo> collectBankerInfo = yxBankerInfos.stream().filter(yxBankerInfo -> banker.getId().equals(yxBankerInfo.getBankerId())).collect(Collectors.toList());
            YxBankerInfo yxBankerInfo = null;
            if (!CollectionUtils.isEmpty(collectBankerInfo)) {
                yxBankerInfo = collectBankerInfo.get(0);
            }
            List<YxReconciliationOrders> collectOrder = reconciliationOrdersList.stream().filter(orders -> banker.getId().equals(orders.getBankerId())).collect(Collectors.toList());
            Integer orderSize = 0;
            BigDecimal ordersMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collectOrder)) {
                orderSize = collectOrder.size();
                ordersMoney = collectOrder.stream()
                        .filter(order -> order.getTotalMoney() != null)
                        .map(YxReconciliationOrders::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            List<YxReconciliationReturn> returnOrders = reconciliationReturnList.stream().filter(YxReconciliationReturn -> banker.getId().equals(YxReconciliationReturn.getBankerId())).collect(Collectors.toList());
            Integer returnSize = 0;
            BigDecimal returnMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(returnOrders)) {
                returnSize = returnOrders.size();
                returnMoney = returnOrders.stream()
                        .filter(returnGoods -> returnGoods.getTotalMoney() != null)
                        .map(YxReconciliationReturn::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            Integer orderSum = orderSize + returnSize;
            if (0 == orderSum) {
                return;
            }
            //账单
            YxReconciliation yxReconciliation = YxReconciliation.builder()
                    .bankerId(banker.getId())
                    .status(ReconciliationStatusEnums.WAIT.getStatus())
                    .reconciliationStartDate(finalStartTime)
                    .reconciliationEndDate(finalEndTime)
                    .orderSum(orderSum)
                    .settlementAmount(ordersMoney.subtract(returnMoney))
                    .creditCardNumbers(null != yxBankerInfo ? yxBankerInfo.getCreditCardNumbers() : "")
                    .bankHouse(null != yxBankerInfo ? yxBankerInfo.getBankHouse() : "")
                    .failRemark(null)
                    .createTime(new Date())
                    .ordersAmount(ordersMoney)
                    .returnGoodsAmount(returnMoney)
                    .otherAmount(BigDecimal.ZERO)
                    .build();
            Integer count = reconciliationMapper.insertSelective(yxReconciliation);
            if (count < 1) {
                log.error("==========插入账单异常==========yxReconciliation::{}", JSONObject.toJSONString(yxReconciliation));
                return;
            }
            //插入账单的订单信息
            collectOrder.stream().forEach(order -> {
                order.setBankerId(banker.getId());
                order.setReconciliationId(yxReconciliation.getId());
                reconciliationOrdersMapper.insertSelective(order);
            });
//            reconciliationOrdersMapper.insertOrders(collectOrder,banker.getId(),yxReconciliation.getId());
            //插入账单的售后完成信息
            returnOrders.stream().forEach(returnOrder -> {
                List<YxBankerOrder> collect = finalYxBankerOrders.stream().filter(item -> returnOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    returnOrder.setDeliverStatus(Integer.valueOf(collect.get(0).getOrderStatus()));
                }
                returnOrder.setBankerId(banker.getId());
                returnOrder.setReconciliationId(yxReconciliation.getId());
                reconciliationReturnMapper.insertSelective(returnOrder);
            });
        });
    }

    /**
     * 半月结 16号晚上00:00:00 运行一次 (这个月的1号00:00:00 - 15号23:59:59)
     */
    public void verifyReconciliationByFirstMonth() {
        //日结的供应商
        List<YxBanker> yxBankers = getBankersByRepayType(3);
        if (CollectionUtils.isEmpty(yxBankers)) {
            return;
        }
        //供应商详情
        List<Integer> bankerIds = yxBankers.stream().map(YxBanker::getId).collect(Collectors.toList());
        List<YxBankerInfo> yxBankerInfos = getBankerInfoByBankerIds(bankerIds);
        //获取账单时间
        Date startTime = null;
        Date endTime = null;
        Map<String, Object> upMonth = null;
        try {
            upMonth = getLastMonthTimeByFirstMonth();
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdfs.parse(upMonth.get("startDate").toString());
            endTime = sdfs.parse(upMonth.get("endDate").toString());
        } catch (Exception e) {
            log.error("==={}", e);
        }
        //获取时间内的订单
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectRecinciliationByTime(bankerIds, startTime, endTime);
        //获取时间内的售后完成单
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectRecinciliationByTime(bankerIds, startTime, endTime, ReturnGoodsStatusEnums.REFUND.getStatus());
        //售后完成单的订单发货状态
        List<YxBankerOrder> yxBankerOrders = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationReturnList)) {
            List<String> childOrderNoList = reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList());
            yxBankerOrders = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
        }
        Date finalStartTime = startTime;
        Date finalEndTime = endTime;
        List<YxBankerOrder> finalYxBankerOrders = yxBankerOrders;
        yxBankers.stream().forEach(banker -> {
            List<YxBankerInfo> collectBankerInfo = yxBankerInfos.stream().filter(yxBankerInfo -> banker.getId().equals(yxBankerInfo.getBankerId())).collect(Collectors.toList());
            YxBankerInfo yxBankerInfo = null;
            if (!CollectionUtils.isEmpty(collectBankerInfo)) {
                yxBankerInfo = collectBankerInfo.get(0);
            }
            List<YxReconciliationOrders> collectOrder = reconciliationOrdersList.stream().filter(orders -> banker.getId().equals(orders.getBankerId())).collect(Collectors.toList());
            Integer orderSize = 0;
            BigDecimal ordersMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collectOrder)) {
                orderSize = collectOrder.size();
                ordersMoney = collectOrder.stream()
                        .filter(order -> order.getTotalMoney() != null)
                        .map(YxReconciliationOrders::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            List<YxReconciliationReturn> returnOrders = reconciliationReturnList.stream().filter(YxReconciliationReturn -> banker.getId().equals(YxReconciliationReturn.getBankerId())).collect(Collectors.toList());
            Integer returnSize = 0;
            BigDecimal returnMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(returnOrders)) {
                returnSize = returnOrders.size();
                returnMoney = returnOrders.stream()
                        .filter(returnGoods -> returnGoods.getTotalMoney() != null)
                        .map(YxReconciliationReturn::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            Integer orderSum = orderSize + returnSize;
            if (0 == orderSum) {
                return;
            }
            //账单
            YxReconciliation yxReconciliation = YxReconciliation.builder()
                    .bankerId(banker.getId())
                    .status(ReconciliationStatusEnums.WAIT.getStatus())
                    .reconciliationStartDate(finalStartTime)
                    .reconciliationEndDate(finalEndTime)
                    .orderSum(orderSum)
                    .settlementAmount(ordersMoney.subtract(returnMoney))
                    .creditCardNumbers(null != yxBankerInfo ? yxBankerInfo.getCreditCardNumbers() : "")
                    .bankHouse(null != yxBankerInfo ? yxBankerInfo.getBankHouse() : "")
                    .failRemark(null)
                    .createTime(new Date())
                    .ordersAmount(ordersMoney)
                    .returnGoodsAmount(returnMoney)
                    .otherAmount(BigDecimal.ZERO)
                    .build();
            Integer count = reconciliationMapper.insertSelective(yxReconciliation);
            if (count < 1) {
                log.error("==========插入账单异常==========yxReconciliation::{}", JSONObject.toJSONString(yxReconciliation));
                return;
            }
            //插入账单的订单信息
            collectOrder.stream().forEach(order -> {
                order.setBankerId(banker.getId());
                order.setReconciliationId(yxReconciliation.getId());
                reconciliationOrdersMapper.insertSelective(order);
            });
            //插入账单的售后完成信息
            returnOrders.stream().forEach(returnOrder -> {
                List<YxBankerOrder> collect = finalYxBankerOrders.stream().filter(item -> returnOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    returnOrder.setDeliverStatus(Integer.valueOf(collect.get(0).getOrderStatus()));
                }
                returnOrder.setBankerId(banker.getId());
                returnOrder.setReconciliationId(yxReconciliation.getId());
                reconciliationReturnMapper.insertSelective(returnOrder);
            });
        });
    }

    /**
     * 半月结 1号晚上00:00:00 运行一次 (上个月的16号00:00:00 - 上个月的最后一天的23:59:59)
     */
    public void verifyReconciliationBySecondMonth() {
        //日结的供应商
        List<YxBanker> yxBankers = getBankersByRepayType(3);
        if (CollectionUtils.isEmpty(yxBankers)) {
            return;
        }
        //供应商详情
        List<Integer> bankerIds = yxBankers.stream().map(YxBanker::getId).collect(Collectors.toList());
        List<YxBankerInfo> yxBankerInfos = getBankerInfoByBankerIds(bankerIds);
        //获取账单时间
        Date startTime = null;
        Date endTime = null;
        Map<String, Object> upMonth = null;
        try {
            upMonth = getLastMonthTimeBySecondMonth();
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdfs.parse(upMonth.get("startDate").toString());
            endTime = sdfs.parse(upMonth.get("endDate").toString());
        } catch (Exception e) {
            log.error("==={}", e);
        }
        //获取时间内的订单
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectRecinciliationByTime(bankerIds, startTime, endTime);
        //获取时间内的售后完成单
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectRecinciliationByTime(bankerIds, startTime, endTime, ReturnGoodsStatusEnums.REFUND.getStatus());
        //售后完成单的订单发货状态
        List<YxBankerOrder> yxBankerOrders = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationReturnList)) {
            List<String> childOrderNoList = reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList());
            yxBankerOrders = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
        }
        Date finalStartTime = startTime;
        Date finalEndTime = endTime;
        List<YxBankerOrder> finalYxBankerOrders = yxBankerOrders;
        yxBankers.stream().forEach(banker -> {
            List<YxBankerInfo> collectBankerInfo = yxBankerInfos.stream().filter(yxBankerInfo -> banker.getId().equals(yxBankerInfo.getBankerId())).collect(Collectors.toList());
            YxBankerInfo yxBankerInfo = null;
            if (!CollectionUtils.isEmpty(collectBankerInfo)) {
                yxBankerInfo = collectBankerInfo.get(0);
            }
            List<YxReconciliationOrders> collectOrder = reconciliationOrdersList.stream().filter(orders -> banker.getId().equals(orders.getBankerId())).collect(Collectors.toList());
            Integer orderSize = 0;
            BigDecimal ordersMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collectOrder)) {
                orderSize = collectOrder.size();
                ordersMoney = collectOrder.stream()
                        .filter(order -> order.getTotalMoney() != null)
                        .map(YxReconciliationOrders::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            List<YxReconciliationReturn> returnOrders = reconciliationReturnList.stream().filter(YxReconciliationReturn -> banker.getId().equals(YxReconciliationReturn.getBankerId())).collect(Collectors.toList());
            Integer returnSize = 0;
            BigDecimal returnMoney = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(returnOrders)) {
                returnSize = returnOrders.size();
                returnMoney = returnOrders.stream()
                        .filter(returnGoods -> returnGoods.getTotalMoney() != null)
                        .map(YxReconciliationReturn::getTotalMoney)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            Integer orderSum = orderSize + returnSize;
            if (0 == orderSum) {
                return;
            }
            //账单
            YxReconciliation yxReconciliation = YxReconciliation.builder()
                    .bankerId(banker.getId())
                    .status(ReconciliationStatusEnums.WAIT.getStatus())
                    .reconciliationStartDate(finalStartTime)
                    .reconciliationEndDate(finalEndTime)
                    .orderSum(orderSum)
                    .settlementAmount(ordersMoney.subtract(returnMoney))
                    .creditCardNumbers(null != yxBankerInfo ? yxBankerInfo.getCreditCardNumbers() : "")
                    .bankHouse(null != yxBankerInfo ? yxBankerInfo.getBankHouse() : "")
                    .failRemark(null)
                    .createTime(new Date())
                    .ordersAmount(ordersMoney)
                    .returnGoodsAmount(returnMoney)
                    .otherAmount(BigDecimal.ZERO)
                    .build();
            Integer count = reconciliationMapper.insertSelective(yxReconciliation);
            if (count < 1) {
                log.error("==========插入账单异常==========yxReconciliation::{}", JSONObject.toJSONString(yxReconciliation));
                return;
            }
            //插入账单的订单信息
            collectOrder.stream().forEach(order -> {
                order.setBankerId(banker.getId());
                order.setReconciliationId(yxReconciliation.getId());
                reconciliationOrdersMapper.insertSelective(order);
            });
            //插入账单的售后完成信息
            returnOrders.stream().forEach(returnOrder -> {
                List<YxBankerOrder> collect = finalYxBankerOrders.stream().filter(item -> returnOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    returnOrder.setDeliverStatus(Integer.valueOf(collect.get(0).getOrderStatus()));
                }
                returnOrder.setBankerId(banker.getId());
                returnOrder.setReconciliationId(yxReconciliation.getId());
                reconciliationReturnMapper.insertSelective(returnOrder);
            });
        });
    }

    /**
     * 根据供应商的结算类型获取
     *
     * @param repayType
     * @return
     */
    public List<YxBanker> getBankersByRepayType(Integer repayType) {
        Example bankerExample = new Example(YxBanker.class);
        bankerExample.createCriteria().andEqualTo("repayType", repayType);
        return bankerMapper.selectByExample(bankerExample);
    }

    /**
     * 根据供应商id获取供应商详情
     *
     * @param bankerIds
     * @return
     */
    public List<YxBankerInfo> getBankerInfoByBankerIds(List<Integer> bankerIds) {
        Example bankerInfoExample = new Example(YxBankerInfo.class);
        bankerInfoExample.createCriteria().andIn("bankerId", bankerIds);
        bankerInfoExample.selectProperties("bankerId", "bankHouse", "creditCardNumbers");
        return bankerInfoMapper.selectByExample(bankerInfoExample);
    }

    /**
     * 得到上周开始截至时间
     *
     * @return
     */
    public static Map<String, Object> upWeek() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");//注意后面有一个空格
        Calendar calStart = Calendar.getInstance();
        Calendar calEnd = Calendar.getInstance();
        calStart.add(Calendar.DAY_OF_MONTH, -7);//上一周
        calEnd.add(Calendar.DAY_OF_MONTH, -7);
        calStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calEnd.setFirstDayOfWeek(Calendar.MONDAY);
        calEnd.set(Calendar.DAY_OF_WEEK, calEnd.getFirstDayOfWeek() + 6);
        Timestamp weekStart = Timestamp.valueOf(format.format(calStart.getTime()) + "00:00:00");//字符串类型转化为timestamp
        Timestamp weekEnd = Timestamp.valueOf(format.format(calEnd.getTime()) + "23:59:59");
        System.out.println(weekStart);
        System.out.println(weekEnd);

        Map<String, Object> result = new HashMap<>();
        result.put("weekStart", weekStart);
        result.put("weekEnd", weekEnd);
        return result;
    }

    /**
     * 获取上个月月开始时间和结束时间
     *
     * @return
     */
    public static Map getLastMonthTime(Integer day) throws Exception {
        Long startTime = getLastMonthStartTime(day);
        Long endTime = getLastMonthEndTime();
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
        String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
        Map map = new HashMap();
        map.put("startDate", startTimeStr);
        map.put("endDate", endTimeStr);
        return map;
    }

    /**
     * 获取上个月月开始时间和结束时间
     *
     * @return
     */
    public static Map getLastMonthTimeByFirstMonth() throws Exception {
        Long startTime = getLastMonthStartTimeByNowMon(1);
        Long endTime = getLastMonthEndTimeBy15();
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
        String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
        Map map = new HashMap();
        map.put("startDate", startTimeStr);
        map.put("endDate", endTimeStr);
        return map;
    }

    /**
     * 获取上个月月开始时间和结束时间
     *
     * @return
     */
    public static Map getLastMonthTimeBySecondMonth() throws Exception {
        Long startTime = getLastMonthStartTime(16);
        Long endTime = getLastMonthEndTime();
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
        String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
        Map map = new HashMap();
        map.put("startDate", startTimeStr);
        map.put("endDate", endTimeStr);
        return map;
    }

    /**
     * 获取一个月几号最开始的一天
     * day 几号
     *
     * @return
     * @throws Exception
     */
    public static Long getLastMonthStartTime(Integer day) throws Exception {
        Long currentTime = System.currentTimeMillis();
        String timeZone = "GMT+8:00";
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(currentTime);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, day);// 设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }


    /**
     * 获取本月15号结束的时间
     *
     * @return
     */
    public static Long getLastMonthEndTimeBy15() {
        Long currentTime = System.currentTimeMillis();
        String timeZone = "GMT+8:00";
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(currentTime);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 15);// 获取当前月15号
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取上个月最后的一天
     *
     * @return
     */
    public static Long getLastMonthEndTime() {
        Long currentTime = System.currentTimeMillis();
        String timeZone = "GMT+8:00";
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(currentTime);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前月最后一天
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    /**
     * 本月的day开始时间
     *
     * @param day
     * @return
     * @throws Exception
     */
    public static Long getLastMonthStartTimeByNowMon(Integer day) throws Exception {
        Long currentTime = System.currentTimeMillis();
        String timeZone = "GMT+8:00";
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(currentTime);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, day);// 设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    public CommonResult audit(Integer id, String auditType, String failRemark) {
        YxReconciliation yxReconciliation = reconciliationMapper.selectByPrimaryKey(id);
        if (null == yxReconciliation) {
            throw new ApiException("账单不存在");
        }
        if (auditType.equals("success")) {
            yxReconciliation.setStatus(ReconciliationStatusEnums.WAIT_REMIT.getStatus());
            reconciliationMapper.updateByPrimaryKeySelective(yxReconciliation);
        } else {
            if (StringUtils.isBlank(failRemark)) {
                throw new ApiException("请填写失败原因");
            }
            yxReconciliation.setStatus(ReconciliationStatusEnums.FAIL.getStatus());
            yxReconciliation.setFailRemark(failRemark);
            reconciliationMapper.updateByPrimaryKeySelective(yxReconciliation);
        }
        return CommonResult.success();
    }

    public CommonResult uploadVoucher(Integer id, String voucherImg) {
        YxReconciliation yxReconciliation = reconciliationMapper.selectByPrimaryKey(id);
        if (!yxReconciliation.getStatus().equals(ReconciliationStatusEnums.WAIT_REMIT.getStatus())) {
            throw new ApiException("状态为待打款才能上传凭证");
        }
        yxReconciliation.setStatus(ReconciliationStatusEnums.SUCCESS.getStatus());
        yxReconciliation.setVoucherImg(voucherImg);
        reconciliationMapper.updateByPrimaryKeySelective(yxReconciliation);
        return CommonResult.success();
    }

    /**
     * 账单上传其他金额表格文件
     * @param reconciliationOtherMoneyRequestList
     * @param reconciliationId (账单id)
     * @param fileName (表格名)
     * @param source (表格来源 "banker","supplyChain")
     */
    public Map uploadDate(List<ReconciliationOtherMoneyRequest> reconciliationOtherMoneyRequestList, Integer reconciliationId, String fileName, String source) {
        List<String> childOrderNoList = reconciliationOtherMoneyRequestList.stream().filter(item -> StringUtils.isNotBlank(item.getChildOrderNo())).map(ReconciliationOtherMoneyRequest::getChildOrderNo).collect(Collectors.toList());
        if (childOrderNoList.size() < reconciliationOtherMoneyRequestList.size()){
            throw new ApiException("每条数据的订单号不能为空");
        }
        //先查询该渠道账单的其他金额数据是否存在
        Example example = new Example(YxReconciliationOtherMoney.class);
        example.createCriteria().andEqualTo("reconciliationId", reconciliationId).andEqualTo("source", source);
        List<YxReconciliationOtherMoney> yxReconciliationOtherMonies = reconciliationOtherMoneyMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxReconciliationOtherMonies)) {
            //存在就删除
            reconciliationOtherMoneyMapper.deleteByExample(example);
        }
        List<ReconciliationOtherMoneyRequest> list = reconciliationOtherMoneyRequestList.stream()
                .map(item -> {
                    item.setReconciliationId(reconciliationId);
                    item.setFileName(fileName);
                    item.setSource(source);
                    item.setCreateTime(new Date());
                    return item;
                }).collect(Collectors.toList());
        list.stream().forEach(item -> {
            YxReconciliationOtherMoney yxReconciliationOtherMoney = new YxReconciliationOtherMoney();
            BeanUtils.copyProperties(item, yxReconciliationOtherMoney);
            reconciliationOtherMoneyMapper.insert(yxReconciliationOtherMoney);
        });

        //判断上传的子订单号是否正常
        Example reconciliationOrdersExample = new Example(YxReconciliationOrders.class);
        reconciliationOrdersExample.createCriteria().andEqualTo("reconciliationId",reconciliationId).andIn("childOrderNo",childOrderNoList);
        reconciliationOrdersExample.selectProperties("childOrderNo");
        List<YxReconciliationOrders> reconciliationOrdersList = reconciliationOrdersMapper.selectByExample(reconciliationOrdersExample);
        List<String> childOrderNos = reconciliationOrdersList.stream().map(YxReconciliationOrders::getChildOrderNo).collect(Collectors.toList());
        Example reconciliationReturnExample = new Example(YxReconciliationReturn.class);
        reconciliationReturnExample.createCriteria().andEqualTo("reconciliationId",reconciliationId).andIn("childOrderNo",childOrderNoList);
        reconciliationReturnExample.selectProperties("childOrderNo");
        List<YxReconciliationReturn> reconciliationReturnList = reconciliationReturnMapper.selectByExample(reconciliationReturnExample);
        childOrderNos.addAll(reconciliationReturnList.stream().map(YxReconciliationReturn::getChildOrderNo).collect(Collectors.toList()));
        //把不存在这账单里的子订单号剔除出来
        Integer failNum = 0;
        List<String> orderNoList = childOrderNoList.stream().filter(childOrderNo ->!childOrderNos.contains(childOrderNo)).collect(Collectors.toList());

        Example example1 = new Example(YxReconciliationOtherMoney.class);
        if (CollectionUtils.isEmpty(orderNoList)){
            example1.createCriteria().andEqualTo("reconciliationId", reconciliationId);
        }else {
            failNum = orderNoList.size();
            example1.createCriteria().andEqualTo("reconciliationId", reconciliationId).andNotIn("childOrderNo",orderNoList);
        }
        List<YxReconciliationOtherMoney> otherMonies = reconciliationOtherMoneyMapper.selectByExample(example1);
        if (!CollectionUtils.isEmpty(otherMonies)){
            //应加金额总数
            BigDecimal addMoney = otherMonies.stream()
                    .filter(item -> item.getAddMoney() != null)
                    .map(YxReconciliationOtherMoney::getAddMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //应扣金额总数
            BigDecimal subtractMoney = otherMonies.stream()
                    .filter(item -> item.getSubtractMoney() != null)
                    .map(YxReconciliationOtherMoney::getSubtractMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            //修改账单的其他金额
            YxReconciliation yxReconciliation = new YxReconciliation();
            yxReconciliation.setId(reconciliationId);
            yxReconciliation.setOtherAmount(addMoney.subtract(subtractMoney));
            reconciliationMapper.updateByPrimaryKeySelective(yxReconciliation);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("successNum",reconciliationOtherMoneyRequestList.size()-failNum);//成功的数量
        map.put("failNum",failNum);//失败的数量
        List<Map<String,String>> mapList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderNoList)){
            orderNoList.forEach(item ->{
                Map<String,String> map1 = new HashMap<>();
                map1.put("childOrderNo",item);
                map1.put("failRemark","订单不属于该账单中");
                mapList.add(map1);
            });
        }
        map.put("failChildOrderNo",mapList);
        return map;
    }

    public CommonResult getFileName(Integer reconciliationId) {
        List<OtherMoneyResponse> list = reconciliationOtherMoneyMapper.selectByReconciliationId(reconciliationId);
        return CommonResult.success(list);
    }

    public CommonResult getOtherMoneyDate(Integer reconciliationId,String source) {
        Example example = new Example(YxReconciliationOtherMoney.class);
        example.createCriteria().andEqualTo("reconciliationId",reconciliationId).andEqualTo("source",source);
        List<YxReconciliationOtherMoney> yxReconciliationOtherMonies = reconciliationOtherMoneyMapper.selectByExample(example);
        return CommonResult.success(yxReconciliationOtherMonies);
    }

    public CommonResult downloadReconciliation(Integer reconciliationId) {
        YxReconciliation yxReconciliation = reconciliationMapper.selectByPrimaryKey(reconciliationId);
        if (null == yxReconciliation){
            throw new ApiException("账单不存在");
        }
        YxBanker banker = bankerMapper.selectByPrimaryKey(yxReconciliation.getBankerId());
        List<ReconciliationDTO> reconciliationDTOList = reconciliationOrdersMapper.selectByReconciliationId(reconciliationId);
        List<YxReturnGoods> yxReturnGoodsList = new ArrayList<>();
        List<String> childOrderNoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(reconciliationDTOList)){
            childOrderNoList = reconciliationDTOList.stream().map(ReconciliationDTO::getChildOrderNo).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(childOrderNoList)) {
                if (childOrderNoList.size() >= 20) {
                    int num = childOrderNoList.size() / 20;
                    int more = childOrderNoList.size() % 20;
                    if (more > 0) {
                        num = num + 1;
                    }
                    for (int i = 0; i < num - 1; i++) {
                        yxReturnGoodsList.addAll(returnGoodsMapper.selectByChildOrderNoList(childOrderNoList.subList(i * 20, i * 20 + 20)));
                    }
                    yxReturnGoodsList.addAll(returnGoodsMapper.selectByChildOrderNoList(childOrderNoList.subList((num - 1) * 20, childOrderNoList.size())));
                } else {
                    yxReturnGoodsList = returnGoodsMapper.selectByChildOrderNoList(childOrderNoList);
                }
            }
        }
        if (!CollectionUtils.isEmpty(yxReturnGoodsList)){
            List<YxReturnGoods> finalYxReturnGoodsList = yxReturnGoodsList;
            reconciliationDTOList.stream().forEach(item ->{
                List<YxReturnGoods> collect = finalYxReturnGoodsList.stream().filter(yxReturnGoods -> item.getChildOrderNo().equals(yxReturnGoods.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)){
                    item.setServiceNo(collect.get(0).getServiceNo());
                    item.setReturnStatus(collect.get(0).getStatus());
                    if (item.getOrderStatus() == 4){
                        item.setReturnDate(collect.get(0).getUpdateTime());
                    }
                }
            });
        }
        List<ReconciliationDTO> reconciliationDTOS = reconciliationReturnMapper.selectByReconciliationId(reconciliationId);
        if (!CollectionUtils.isEmpty(reconciliationDTOS)){
            List<ReconciliationDTO> collect = reconciliationDTOS.stream().map(item -> {
                item.setOrderStatus(4);
                item.setReturnMoney(item.getCostPrice().multiply(BigDecimal.valueOf(item.getProductSum())));
                return item;
            }).collect(Collectors.toList());
            List<String> collect1 = collect.stream().map(ReconciliationDTO::getChildOrderNo).collect(Collectors.toList());
            childOrderNoList.addAll(collect1);
            reconciliationDTOList.addAll(reconciliationDTOS);
        }
        if (!CollectionUtils.isEmpty(reconciliationDTOList)){
            List<YxBankerOrder> yxBankerOrderList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(childOrderNoList)) {
                if (childOrderNoList.size() >= 20) {
                    int num = childOrderNoList.size() / 20;
                    int more = childOrderNoList.size() % 20;
                    if (more > 0) {
                        num = num + 1;
                    }
                    for (int i = 0; i < num - 1; i++) {
                        yxBankerOrderList.addAll(bankerOrderMapper.selectByChildOrderNoList(childOrderNoList.subList(i * 20, i * 20 + 20)));
                    }
                    yxBankerOrderList.addAll(bankerOrderMapper.selectByChildOrderNoList(childOrderNoList.subList((num - 1) * 20, childOrderNoList.size())));
                } else {
                    yxBankerOrderList = bankerOrderMapper.selectByChildOrderNoList(childOrderNoList);
                }
            }
            List<YxBankerOrder> finalYxBankerOrderList = yxBankerOrderList;
            reconciliationDTOList.stream().forEach(item ->{
                List<YxBankerOrder> collect = finalYxBankerOrderList.stream().filter(yxBankerOrder -> yxBankerOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)){
                    item.setExpressCode(collect.get(0).getExpressCode());
                    item.setExpressNo(collect.get(0).getExpressNo());
                    item.setOrderDate(collect.get(0).getCreateTime());
                }
                item.setBankerName(banker.getName());
            });
        }
        return CommonResult.success(reconciliationDTOList);
    }

    public CommonResult submitReconciliation(Integer reconciliationId) {
        YxReconciliation yxReconciliation = reconciliationMapper.selectByPrimaryKey(reconciliationId);
        yxReconciliation.setStatus(ReconciliationStatusEnums.ING.getStatus());
        yxReconciliation.setFailRemark(null);
        return CommonResult.success(reconciliationMapper.updateByPrimaryKey(yxReconciliation));
    }
}
